﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects.DataClasses;
using System.Data.Objects;

namespace SlFrame.Core
{
    public abstract class EfRepositoryBase<T> where T : EntityObject, new()
    {
        public bool Insert(T t)
        {
            using (ModelContainer container = new ModelContainer())
            {
                container.CreateObjectSet<T>().AddObject(t);
                if (container.SaveChanges() > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public bool Update(T t)
        {
            using (ModelContainer container = new ModelContainer())
            {
                container.CreateObjectSet<T>().Attach(t);
                if (container.SaveChanges() > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public bool Delete(T t)
        {
            using (ModelContainer container = new ModelContainer())
            {
                ObjectSet<T> os = container.CreateObjectSet<T>();
                os.Attach(t);
                os.DeleteObject(t);
                if (container.SaveChanges() > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public T Find(List<KeyValuePair<string, object>> keys)
        {
            using (ModelContainer container = new ModelContainer())
            {
                object obj = container.GetObjectByKey(
                    new System.Data.EntityKey(container.CreateObjectSet<T>().EntitySet.Name, keys));
                if (obj == null)
                {
                    return default(T);
                }
                else
                {
                    return (T)obj;
                }
            }
        }

        public List<T> FindAll()
        {
            using (ModelContainer container = new ModelContainer())
            {
                return container.CreateObjectSet<T>().ToList<T>();
            }
        }
    }
}
